package it.tcm.TeacherClassMate.action;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import it.tcm.TeacherClassMate.beans.MailBean;
import it.tcm.TeacherClassMate.beans.OrderMainBean;
import it.tcm.TeacherClassMate.beans.SessionUser;
import it.tcm.TeacherClassMate.facade.MailManageBase;
import it.tcm.TeacherClassMate.facade.OrderMainManageBase;
import it.tcm.TeacherClassMate.persistent.DBConnection;
import it.tcm.TeacherClassMate.util.SendMail;
import it.tcm.TeacherClassMate.util.Util;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;



public class SendZipMailAction extends Action {

	// --------------------------------------------------------- Instance Variables

	// --------------------------------------------------------- Methods


	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * 
	 */

	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) 
	{		
		  logger.info("SEND ZIP MAIL ACTION");
		 
		 
		  Blob docx = null;
		  Blob result = null;
		  Connection conn = null;
		  Statement stmt0 = null;
		  Statement stmt1 = null;
		  ResultSet rs0 = null;
		  ResultSet rs1 = null;
		  
		  try{
				
			  SessionUser sessionUser = (SessionUser) request.getSession().getAttribute("sessionUser");
			  
			  String id = request.getParameter("id");
			  OrderMainManageBase ommb = new OrderMainManageBase();
			  OrderMainBean omb = ommb.getOrderMainById(Integer.valueOf(id));
			  Long time = new Long(new Date().getTime());
			  DBConnection db = new DBConnection();
			  conn = db.getDBConnection();	
			  // These are the files to include in the ZIP file
			  String[] filenames = new String[]{omb.getUserId() + "-" + time.toString() + "_verifica.docx", omb.getUserId() + "-" + time.toString() + "_risultato.docx"};
			  InputStream[] inputstreams = new  InputStream[2];
			  
			  stmt0 = conn.createStatement();
			  rs0 = stmt0.executeQuery("select DOCX from ORDERMAIN where id = " + id);
			  if (rs0.next()) {
				  docx = rs0.getBlob(1);
				  inputstreams[0] = docx.getBinaryStream();
			  }
			  
			  stmt1 = conn.createStatement();
			  rs1 = stmt1.executeQuery("select RESULT from ORDERMAIN where id = " + id);
			  if (rs1.next()) {
				  result = rs1.getBlob(1);
				  inputstreams[1] = result.getBinaryStream();
			  }

			  // Create a buffer for reading the files
			  byte[] buf = new byte[1024];

		      // Create the ZIP file
			  Context ctx = new InitialContext();
			  String docxFileDir = (String)ctx.lookup("java:comp/env/docxPath");
		      String outFilename = docxFileDir + "//" + "verifica" + time.toString() + ".zip";
		      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));

		      // Compress the files
		      for (int i=0; i<filenames.length; i++) {

		          // Add ZIP entry to output stream.
		          out.putNextEntry(new ZipEntry(filenames[i]));

		          // Transfer bytes from the file to the ZIP file
		          int len;
		          while ((len = inputstreams[i].read(buf)) > 0) {
		              out.write(buf, 0, len);
		          }

		          // Complete the entry
		          out.closeEntry();
		          inputstreams[i].close();
		      }

		      // Complete the ZIP file
		      out.close();
		      
		      try {
					MailBean mailBean = new MailBean();
					mailBean.setType("2");
					mailBean.setDest(sessionUser.getEmail());
					mailBean.setBody("VerificaFast");
					mailBean.setLock("0");
					mailBean.setSent("0");
					mailBean.setObject("VerificaFast");
					mailBean.setFailed(0);
					mailBean.setFilename("verifica" + time.toString() + ".zip");
					mailBean.setFile(outFilename);
					MailManageBase mmb = new MailManageBase();
					Integer i = mmb.save(mailBean);
					logger.info("mail with id " + i + " saved");
				} catch (Exception e) {
					logger.error("Exception while saving mail : " + e);
				}
		      	      		      
		      request.setAttribute(Util.MAIL_SENDED,"YES"); 
		      omb.setDownloaded(1);
			  ommb.save(omb);

		  } catch (Throwable e) {
				 System.out.println("catch exception " +  e.getMessage()); 
				  e.printStackTrace();
		  } finally {
				  try {
				  rs0.close();
				  stmt0.close();
				  conn.close();
				  } catch (SQLException e) {
				  e.printStackTrace();
			  }
		  }
		
		 // creo il documento dei risultati
		 return mapping.findForward("gotodownload"); 
		 
	}
	
	
}